import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/index")
public class IndexServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //根据用户请求中的sessionId，获取到用户信息并显示在页面上
        resp.setContentType("text/html;charset=utf-8");
        //1.判断当前用户是否已经登录
        HttpSession httpSession = req.getSession(false);
        if(httpSession==null){
            //如果当前会话不存在，则说明用户尚未登录，重定向到login.html
            resp.sendRedirect("login.html");
            return;
        }
        //2.如果用户已经登录，就可以从HttpSession中拿到用户信息了
        String username = (String) httpSession.getAttribute("username");
        Integer loginCount = (Integer) httpSession.getAttribute("loginCount");
        loginCount=loginCount+1;
        httpSession.setAttribute("loginCount",loginCount);
        //3.返回一个html页面
        StringBuilder html = new StringBuilder();
        html.append("<div>用户:"+username+"</div>");
        html.append("<div>访问次数"+loginCount+"</div>");
        resp.getWriter().write(html.toString());
    }
}
